package easycloud.ecs.web.util;

import java.io.IOException;

import javax.inject.Inject;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import easycloud.ecs.common.domain.User;
import easycloud.ecs.web.service.UserService;

@Service
public class AuthenticationSuccessHandler extends
		SavedRequestAwareAuthenticationSuccessHandler {

	private static final Log logger = LogFactory
			.getLog(AuthenticationSuccessHandler.class);

	@Inject
	private UserService userService;

	private RequestCache requestCache;

	public AuthenticationSuccessHandler() {
		requestCache = new HttpSessionRequestCache();
	}

	private void bindUserToSession(HttpServletRequest request) {
		SecurityContext sc = SecurityContextHolder.getContext();
		String userName = sc.getAuthentication().getName();
		User user = userService.getUserByEmail(userName);
		logger.debug("Bind User : " + user);
		HttpSession session = request.getSession();
		session.setAttribute(SessionAttributes.CUR_USER, user);
		if (user.getRole().equals(User.Role.ADMIN)) {
			session.setAttribute(SessionAttributes.CUR_ADMIN,
					user);
		}
		session.setAttribute(SessionAttributes.CUR_USER, user);
	}

	@Override
	public void onAuthenticationSuccess(HttpServletRequest request,
			HttpServletResponse response, Authentication authentication)
			throws ServletException, IOException {
		bindUserToSession(request);

		SavedRequest savedRequest = requestCache.getRequest(request, response);

		if (savedRequest == null) {
			response.sendRedirect("home");
			return;
		}

		if (isAlwaysUseDefaultTargetUrl()
				|| StringUtils.hasText(request
						.getParameter(getTargetUrlParameter()))) {
			this.requestCache.removeRequest(request, response);
			super.onAuthenticationSuccess(request, response, authentication);
			return;
		}

		clearAuthenticationAttributes(request);
	}

}
